﻿using System;
using System.Collections.Generic;
using QScheduler.Job;
using Quartz;
using Quartz.Impl;
using Topshelf;

namespace QScheduler
{
    public sealed class ServiceRunner : ServiceControl, ServiceSuspend
    {
        private readonly IScheduler scheduler;

        public ServiceRunner()
        {
            #region 初始化作业调度池、job、trigger

            //首先创建一个作业调度池
            scheduler = StdSchedulerFactory.GetDefaultScheduler();

            //创建出来一个具体的作业
            IJobDetail job = JobBuilder.Create<ClearUselessCacheFile>()
                .WithIdentity("job1", "jobGroup1")
                .Build();

            //创建并配置一个触发器
            DateTimeOffset startTime = DateTime.Now;
            DateTimeOffset endTime = DateTime.Now.AddYears(100);
            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                .WithIdentity("trigger1", "triggerGroup1")
                .StartAt(startTime)
                .EndAt(endTime)
                .WithSimpleSchedule(x => x.WithIntervalInSeconds(900).WithRepeatCount(int.MaxValue))
                .Build();

            //加入作业调度池中
            scheduler.ScheduleJob(job, trigger);

            #endregion
        }

        public bool Start(HostControl hostControl)
        {
            scheduler.Start();
            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            scheduler.Shutdown(false);
            return true;
        }

        public bool Continue(HostControl hostControl)
        {
            scheduler.ResumeAll();
            return true;
        }

        public bool Pause(HostControl hostControl)
        {
            scheduler.PauseAll();
            return true;
        }


    }
}
